//
//  ProgressImageView.swift
//  MicroBlog
//
//  Created by 002 on 15/10/29.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit

class ProgressImageView: UIImageView {

    // 外部传递的进度值 0 ~ 1
    var progress : CGFloat = 0 {
        didSet {
            progressView.progress = progress
        }
    }
    
    init() {
        super.init(frame: CGRectZero)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置UI
    private func setupUI() {
        
        // 1. 添加控件
        addSubview(progressView)
        progressView.backgroundColor = UIColor.clearColor()        
        
        // 2. 布局
        progressView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var progressView : ProgressView = ProgressView()
}


// MARK: - 进度视图
private class ProgressView : UIView {
    
    // 进度值
    var progress : CGFloat = 0 {
        didSet {
            // 重新绘图
            setNeedsDisplay()
        }
    }
    
    // rect: == bounds
    private override func drawRect(rect: CGRect) {

//        super.drawRect(rect)
        
        let center = CGPointMake(rect.width * 0.5, rect.height * 0.5)   // 中心点
        let start = CGFloat(-M_PI_2)   // 起始弧度
        let radius = min(rect.width, rect.height) * 0.5    // 半径
        let end = start + progress * 2 * CGFloat(M_PI)  // 结束弧度
     
        let path = UIBezierPath.init(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
        
        // 添加到中心连线
        path.addLineToPoint(center)
        path.closePath()
        
        UIColor.init(white: 1.0, alpha: 0.3).setFill()
        
        path.fill()
    }

}